# include the required packages.
gulp = require 'gulp'
gutil = require 'gulp-util'
uglify = require "gulp-uglify"
rename = require 'gulp-rename'
concat = require 'gulp-concat'
path = require 'path'
fs = require 'fs-extra'

bower = require 'gulp-bower'

mainBowerFiles = require 'main-bower-files'

del = require 'del'

exec = require('child_process').exec

Q = require 'q'
fscopy = Q.denodeify fs.copy


webpack = require 'webpack'
webpackConfig = require './webpack.config'

# 样式编译
(require './gulp_script/gulp-stylus') gulp
(require './gulp_script/gulp-runtime') gulp

# 下载bower依赖
gulp.task 'bower:download', -> bower()

# 删除vendor
gulp.task 'clean:vendor', (cb) -> del ['static/vendor'], cb

gulp.task 'clean:dist', (cb) -> del ['static-dist'], cb

# 根据mainfile配置抽取需要的文件到vendor目录
gulp.task 'bower:install', ['bower:download', 'clean:vendor'], ->
  gulp.src mainBowerFiles(), {base: 'bower_components'}
  .pipe gulp.dest 'static/vendor/'


# 生产webpack构建
gulp.task 'webpack:build', ['bower:install', 'clean:dist', 'runtime:w-loader'], (callback)->
  process.env.NODE_ENV= "production"
  exec "webpack --config ./webpack.config.coffee", (err, stdout, stderr) ->
    throw new gutil.PluginError('build', err) if (err)

# 开发webpack构建
gulp.task 'webpack:build-dev', [ 'bower:install', 'copy:bower'], ->
  exec "webpack --config ./webpack.config.coffee", (err, stdout, stderr) ->
    throw new gutil.PluginError('build', err) if (err)

# 复制例外文件
gulp.task 'copy:static', ['bower:install', 'clean:dist', 'min:jquery', 'copy:fonts', 'copy:images'], ->
  fscopy 'static/favicon.ico', 'static-dist/favicon.ico'

#min jquery
gulp.task 'min:jquery', ['bower:install', 'clean:dist'], ->
  gulp.src('static/vendor/jquery/dist/jquery.js')
  .pipe(uglify())    #压缩
  .pipe rename(extname: '.min.js')
  .pipe(gulp.dest('static-dist/vendor/jquery/dist'));  #输出目录

#copy fonts
gulp.task 'copy:fonts', ['bower:install', 'clean:dist'], ->
  fscopy 'static/sys/fonts', 'static-dist/sys/fonts'

#copy images
gulp.task 'copy:images', ['bower:install', 'clean:dist'], ->
  fscopy 'static/sys/images', 'static-dist/sys/images'


#copy bower
gulp.task 'copy:bower', ['bower:install', 'clean:dist'], ->
  fscopy 'bower_components/layer', 'static/vendor/layer'
  fscopy 'bower_components/layer', 'static-dist/vendor/layer'

# debug 打包
gulp.task 'default', ['compress-stylus', 'webpack:build-dev']
# 编译打包
gulp.task 'dist', ['clean:dist', 'webpack:build',  'copy:static', 'compress-stylus:runtime', ]

#合并rweb文件
gulp.task 'rweb', [], ->
  gulp.src('static/sys/js/src/*.js')  #选择合并的JS
  .pipe(concat('rweb.js'))   #合并js
  .pipe(gulp.dest('static/sys/js/dist/'));
